package cn.kzgg.ymcc.userDetails;

import cn.kzgg.ymcc.domain.Login;
import cn.kzgg.ymcc.domain.Permission;
import cn.kzgg.ymcc.mapper.PermissionMapper;
import cn.kzgg.ymcc.service.ILoginService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 复写loadUserByUsername(username)方法加载我们数据库中的用户信息
 * 封装用户信息	并返回
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    /**
     * 加载数据库中的认证的用户的信息：用户名，密码，用户的权限列表
     *
     * @param username: 该方法把username传入进来，我们通过username查询用户的信息
     * (密码，权限列表等)然后封装成 UserDetails进行返回 ，交给security 。
     */

    @Autowired
    private ILoginService loginService;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询登录和权限
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        Login login = loginService.selectOne(wrapper);

        //根据登陆人查权限
        List<Permission> permissions = permissionMapper.loadPermissionByLoginId(login.getId());

        List<SimpleGrantedAuthority> collect = permissions.stream().map(permission ->
                new SimpleGrantedAuthority(permission.getSn())).collect(Collectors.toList());
        return new User(
                login.getUsername(),
                login.getPassword(),
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                collect);


        //密码是基于BCryptPasswordEncoder加密的密文
        //User是security内部的对象，UserDetails的实现类 ，

    }
}